<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <div class="search-bar">
      <el-radio-group v-model="activeName" size="large">
        <el-radio-button label="公有人才库" value="public" />
        <el-radio-button label="私有人才库" value="private" />
        <el-radio-button label="候选人" value="candidate" />
        <el-radio-button label="邀请面试" value="interview" />
        <el-radio-button label="录取" value="admission" />
        <el-radio-button label="不合适" value="improper" />
        <el-radio-button label="储备库" value="reserve" />
      </el-radio-group>
    </div>
    <!-- 筛选表单 -->
    <el-form :model="queryParams" :inline="true" class="filter-form" v-if="activeName !== 'interview'">
      <el-form-item label="姓名:">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="职位类型:">
        <el-input v-model="queryParams.jobName" placeholder="请输入职位类型" clearable />
      </el-form-item>
      <el-form-item label="工作经验:">
        <el-input-number v-model="queryParams.jonLongStart" placeholder="最低" :min="0" :controls="false" style="width: 80px;" />
        <span style="margin: 0 5px;">-</span>
        <el-input-number v-model="queryParams.jonLongEnd" placeholder="最高" :min="0" :controls="false" style="width: 80px;" />
        <span style="margin-left: 5px;">年</span>
      </el-form-item>
      <el-form-item label="城市:">
        <el-input v-model="queryParams.city" placeholder="请输入城市" clearable />
      </el-form-item>
      <el-form-item label="学历:">
        <el-input v-model="queryParams.education" placeholder="请输入学历" clearable />
      </el-form-item>
      <el-form-item label="活跃状态:">
        <el-select v-model="queryParams.activeState" placeholder="请选择活跃状态" clearable style="width: 180px;">
          <el-option
            v-for="item in activeStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="action-buttons" v-if="activeName !== 'interview'">
      <el-button type="primary" @click="openUploadDialog">上传简历</el-button>
      <el-button type="primary" @click="handleRefreshStatus">更新状态</el-button>
      <el-button type="primary" @click="openRuleConfigModal">规则配置</el-button>
    </div>

    <!-- 人才列表 -->
    <div class="resume-list" v-loading="loading" v-if="activeName !== 'interview'">
      <el-card class="resume-item" v-for="item in resumeList" :key="item.id">
        <el-row :gutter="20">
          <!-- 左侧主要信息区域 -->
          <el-col :span="18">
            <div class="resume-header">
              <span class="name">{{ item.name }}</span>
              <el-tag v-if="item.activeState !== undefined" type="warning" size="small" effect="light">
                {{ formatActiveState(item.activeState) }}
              </el-tag>
              <!-- 不合适特定头部标签 -->
              <template v-if="activeName === 'improper'">
                <el-tag size="small" type="danger" effect="plain" style="margin-left: 8px;">要价太高</el-tag>
                <el-tag size="small" type="info" effect="plain" style="margin-left: 8px;">专业不足</el-tag>
              </template>
              <span class="job-title">{{ item.jobName }}</span>
              <span class="phone">{{ item.phone }}</span>
              <!-- 私有人才库特定头部信息 -->
              <template v-if="activeName === 'private'">
                <span class="update-time-display">简历更新时间: {{ formatDate(item.updateTime) }}</span>
                <el-link type="danger" :underline="false" style="margin-left: 5px; font-size: 12px;" @click="handleRefreshSingleResume(item.id)">更新</el-link>
                <span class="matching-score" v-if="item.resumeSource">匹配分数: {{ item.resumeSource }} 分</span>
                <span class="matching-score" v-else>匹配分数: 65 分</span>
              </template>
              <!-- 录取特定头部信息 -->
              <template v-if="activeName === 'admission'">
                <span class="matching-score">匹配分数: {{ item.resumeSource || 65 }} 分</span>
                <span class="interview-time">预计入职时间: {{ item.workingStatus ? '' : '2025-05-01' }}</span>
              </template>
              <!-- 不合适特定头部信息 - 匹配分数 -->
              <template v-if="activeName === 'improper'">
                <span class="matching-score">匹配分数: {{ item.resumeSource || 65 }} 分</span>
              </template>
            </div>
            <div class="basic-info">
              <span v-if="item.sex">{{ formatSex(item.sex) }}</span>
              <span v-if="item.jonLong !== undefined"> | {{ item.jonLong }}年</span>
              <span v-if="item.age"> | {{ item.age }}岁</span>
              <span v-if="item.education"> | {{ item.education }}</span>
              <span v-if="item.jobState"> | {{ item.jobState }}</span>
            </div>
            <div class="experience-list" v-if="item.jobName">
                <div class="experience-item">
                  主要职位: {{ item.jobName }}
                </div>
              </div>
              <div class="education-item" v-if="item.education">
                最高学历: {{ item.education }}
              </div>
              <!-- 新增工作经历展示 -->
              <div class="work-experience-list" v-if="item.workExp && item.workExp.length > 0">
                <div class="section-title">工作经历:</div>
                <div class="work-experience-item" v-for="exp in item.workExp" :key="exp.id">
                  <p><strong>{{ exp.companyName }}</strong> ({{ exp.startTime }} - {{ exp.endTime }})</p>
                  <p>{{ exp.jobName }}</p>
                </div>
              </div>
              
              <!-- 新增教育经历展示 -->
              <div class="education-experience-list" v-if="item.educations && item.educations.length > 0">
                <div class="section-title">教育经历:</div>
                <div class="education-experience-item" v-for="edu in item.educations" :key="edu.id">
                  <p>{{ formatEducationDate(edu.startTime) }}-{{ formatEducationDate(edu.endTime) }} {{ edu.schoolName }} {{ edu.major }} {{ edu.qualification }}</p>
                </div>
              </div>
          </el-col>

          <!-- 右侧操作及标签区域 -->
          <el-col :span="6" class="resume-actions">
            <!-- 通用部分：技能标签、优势 -->
            <div class="skills" v-if="item.tags">
              <span>技能标签:</span>
              <div class="tags-container">
                <el-tag
                  v-for="tag in item.tags ? item.tags.split(',').filter(t => t.trim() !== '') : []"
                  :key="tag"
                  size="small"
                  style="margin-right: 8px; margin-top: 5px; display: inline-block;">
                  {{ tag }}
                </el-tag>
              </div>
            </div>
            <!-- 不合适特定技能标签 -->
            <template v-if="activeName === 'improper' && (!item.tags || item.tags.split(',').filter(t => t.trim() !== '').length === 0)">
              <div class="skills">
                <span>技能标签:</span>
                <div class="tags-container">
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Webpack</el-tag>
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Vue</el-tag>
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Webpack</el-tag>
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Vue</el-tag>
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Webpack</el-tag>
                  <el-tag size="small" style="margin-right: 8px; margin-top: 5px; display: inline-block;">Vue</el-tag>
                </div>
              </div>
            </template>
            <div class="advantages" v-if="activeName !== 'private' && item.advantage"> <!-- 私库中优势通常较大，可能不在此处显示或以不同方式 -->
              <span>优势:</span>
              <div class="advantage-content">{{ item.advantage }}</div>
            </div>

            <!-- 私有人才库特定操作链接 -->
            <template v-if="activeName === 'private'">
              <div class="private-actions">
                <el-link type="primary" style="margin-right: 10px;" @click="showResumeDetail(item.id)">查看简历</el-link>
                <el-link type="primary" :underline="false" style="margin-right: 10px;">发送面试官(催办)</el-link> <!-- 占位 -->
                <br/>
                <el-link type="primary" :underline="false" style="margin-right: 10px; margin-top: 5px;">标签</el-link> <!-- 占位 -->
                <el-link type="primary" :underline="false" style="margin-top: 5px;" @click="openInterviewDialog(item.id)">面试时间</el-link> <!-- 占位 -->
                 <br/>
                <el-link type="primary" :underline="false" style="margin-top: 5px;">问 AI</el-link> <!-- 占位 -->
              </div>
               <div class="advantages" v-if="item.advantage" style="margin-top: 10px;">
                <span>优势:</span>
                <div class="advantage-content">{{ item.advantage }}</div>
              </div>
            </template>
            <!-- 录取人才库特定操作链接 -->
            <template v-else-if="activeName === 'admission'">
              <div class="admission-actions">
                <el-button size="small" @click="handleNotJoined(item.id)">牛人未入职</el-button>
                <el-button size="small" @click="handleJoined(item.id)">已入职</el-button>
                <el-button size="small" @click="handleLeft(item.id)">已离职</el-button>
              </div>
              <div class="update-info" v-if="item.updateTime">
                <span>查看薪资待遇</span>
              </div>
              <div>
                <el-link type="primary" style="margin-right: 10px;" @click="showResumeDetail(item.id)">查看简历</el-link>
                <el-link type="primary" style="margin-right: 10px;" @click="showExpand(item.id)">查看报告</el-link>
              </div>
            </template>
            <!-- 不合适人才库特定操作链接 -->
            <template v-else-if="activeName === 'improper'">
              <div class="actions-container">
                <el-link type="primary" style="margin-right: 10px;" @click="showResumeDetail(item.id)">查看简历</el-link>
                <el-link type="primary" style="margin-right: 10px;">标签</el-link>
              </div>
            </template>
            <!-- 其他人才库操作链接 -->
            <template v-else>
              <div class="update-info" v-if="item.updateTime">
                <span>简历更新时间: {{ formatDate(item.updateTime) }}</span>
                <el-link type="primary" @click="handleRefreshSingleResume(item.id)">更新</el-link>
              </div>
              <div>
                <el-link type="primary" style="margin-right: 10px;" @click="showResumeDetail(item.id)">查看简历</el-link>
                <el-link type="primary" style="margin-right: 10px;">标签</el-link>
                <el-link type="primary">问 AI</el-link>
              </div>
            </template>
          </el-col>
        </el-row>
        <!-- 私有人才库的 AI 评语 -->
        <template v-if="activeName === 'private'">
          <div class="ai-comment-section" v-if="item.aiResumeComment">
            <strong>AI 评语:</strong>
            <MarkdownView :content="item.aiResumeComment" />
          </div>
        </template>
        <!-- 录取人才库的评价展示 -->
        <template v-if="activeName === 'admission'">
          <div class="ai-comment-section" v-if="item.aiResumeComment">
            <strong>AI 评语:</strong>
            <MarkdownView :content="item.aiResumeComment || '性格特点：乐观、外向、喜欢与人交流，具有良好的沟通能力和团队协作精神。技能评估：JavaScript基础扎实，React熟练，有3年前端开发经验。'" />
          </div>
          <div class="evaluation-section" v-if="item.evaluate">
            <strong>面试评语:</strong>
            <MarkdownView :content="item.evaluate || '技术能力：React基础扎实，对组件设计有自己的见解，能够解决常见的性能问题。沟通能力：表达清晰，能够理解业务需求并转化为技术实现。团队协作：之前项目经验丰富，善于与后端开发协作。'" />
          </div>
          <div class="hr-evaluation-section" v-if="item.hrEvaluate">
            <strong>人事评语:</strong>
            <MarkdownView :content="item.hrEvaluate || '面试表现良好，符合团队文化，建议进入下一轮技术面试。薪资期望在25K-30K之间，可接受夜班和加班。'" />
          </div>
        </template>
        <!-- 不合适人才库的评价展示 -->
        <template v-if="activeName === 'improper'">
          <div class="ai-comment-section">
            <strong>AI 评语:</strong>
            <MarkdownView :content="item.aiResumeComment || '性格特点：乐观、外向、喜欢与人交流，具有良好的沟通能力和团队协作精神。技能评估：JavaScript基础扎实，React熟练，有3年前端开发经验。'" />
          </div>
          <div class="evaluation-section">
            <strong>面试评语:</strong>
            <MarkdownView :content="item.evaluate || '技术能力：React基础扎实，对组件设计有自己的见解，能够解决常见的性能问题。沟通能力：表达清晰，能够理解业务需求并转化为技术实现。团队协作：之前项目经验丰富，善于与后端开发协作。'" />
          </div>
          <div class="hr-evaluation-section">
            <strong>人事评语:</strong>
            <MarkdownView :content="item.hrEvaluate || '面试表现良好，符合团队文化，建议进入下一轮技术面试。薪资期望在25K-30K之间，可接受夜班和加班。'" />
          </div>
        </template>
      </el-card>
      <el-empty v-if="!loading && resumeList.length === 0" description="暂无数据" />
    </div>

    <!-- 面试组件 -->
    <InterviewList v-if="activeName === 'interview'" />

    <el-pagination
      v-if="total > 0 && activeName !== 'interview'"
      v-model:current-page="queryParams.pageNo"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="getList"
      @current-change="getList"
      class="mt-4 justify-end"
    />

    <RuleConfigModal v-model:visible="ruleConfigModalVisible" />

    <!-- 上传简历对话框 -->
    <el-dialog title="上传简历" v-model="uploadDialogVisible" width="500px" append-to-body destroy-on-close>
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload
            ref="uploadRef"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :multiple="true"
            accept=".doc,.docx,.pdf"
            :limit="10"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 .doc, .docx, .pdf 格式，最多可上传10个文件</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择AI模型">
          <el-select
            v-model="uploadForm.aiId"
            placeholder="请选择AI模型"
            style="width: 100%;"
            clearable
            filterable
            :loading="isLoadingModels"
          >
            <el-option
              v-for="model in aiModelOptions"
              :key="model.id"
              :label="model.name"
              :value="model.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="uploading" @click="handleUpload">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 简历详情弹窗 -->
    <el-dialog title="简历详情" v-model="resumeDetailVisible" width="90%" height="90%" append-to-body destroy-on-close>
      <div style="height: 80vh;">
        <iframe 
          v-if="resumeUrl" 
          :src="resumeUrl" 
          width="100%" 
          height="100%" 
          frameborder="0"
          style="border: none;"
        ></iframe>
        <div v-else class="text-center" style="padding: 30px; font-size: 16px;">暂无简历内容或加载失败</div>
      </div>
    </el-dialog>

    <!-- 面试时间设置对话框 -->
    <el-dialog title="设置面试时间" v-model="interviewDialogVisible" width="400px" append-to-body destroy-on-close>
      <el-form :model="interviewForm" label-width="100px">
        <el-form-item label="面试类型">
          <el-input v-model="interviewForm.viewName" placeholder="请输入面试类型，如：初面/技术面" />
        </el-form-item>
        <el-form-item label="面试时间">
          <el-date-picker
            v-model="interviewForm.viewTime"
            type="datetime"
            placeholder="选择面试时间"
            style="width: 100%;"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="interviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInterviewTime">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import RuleConfigModal from './RuleConfigModal.vue'
import { PersonnelResumeApi, type PersonnelResumeVO } from '@/api/hrm/personnelresume'
import { ElMessage, ElUpload } from 'element-plus'
import { ModelApi, type ModelVO } from '@/api/ai/model/model'
import InterviewList from './components/InterviewList.vue'
import MarkdownView from '@/components/MarkdownView/index.vue'

defineOptions({ name: 'PersonnelResume' })

const loading = ref(true)
const resumeList = ref<PersonnelResumeVO[]>([])
const total = ref(0)

const activeName = ref('public')

const queryParams = reactive<{
  pageNo: number
  pageSize: number
  name?: string
  activeState?: number
  jobName?: string
  jonLongStart?: number
  jonLongEnd?: number
  city?: string
  education?: string
  permission?: string // 权限 公海-'public',私海-'private'
  candidate?: boolean // 是否候选
  invitation?: boolean // 是否邀面
  reserve?: boolean // 是否储备
  admission?: boolean // 是否合适 (录取/不合适)
}>({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  activeState: undefined,
  jobName: undefined,
  jonLongStart: undefined,
  jonLongEnd: undefined,
  city: undefined,
  education: undefined,
  permission: 'public', // 默认公海
  candidate: undefined,
  invitation: undefined,
  reserve: undefined,
  admission: undefined
})

const ruleConfigModalVisible = ref(false)

// 上传相关
const uploadDialogVisible = ref(false)
const uploadRef = ref<InstanceType<typeof ElUpload>>()
const uploading = ref(false)
const uploadFiles = ref<File[]>([])
const uploadForm = reactive({
  aiId: undefined as number | undefined
})

// AI模型选项
const aiModelOptions = ref<ModelVO[]>([])
const isLoadingModels = ref(false)

// 获取AI模型列表
const fetchAiModels = async () => {
  isLoadingModels.value = true
  try {
    const data = await ModelApi.getModelSimpleList(1)
    aiModelOptions.value = data || []
    
    // 默认选择第一个AI模型
    if (aiModelOptions.value.length > 0) {
      uploadForm.aiId = aiModelOptions.value[0].id
    }
  } catch (error) {
    console.error('Failed to fetch AI models:', error)
    ElMessage.error('获取AI模型列表失败')
  } finally {
    isLoadingModels.value = false
  }
}

const getList = async () => {
  loading.value = true
  try {
    const data = await PersonnelResumeApi.getPersonnelResumePage(queryParams)
    resumeList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error("Failed to fetch resume list:", error)
  } finally {
    loading.value = false
  }
}

watch(activeName, (newValue) => {
  queryParams.permission = undefined
  queryParams.candidate = undefined
  queryParams.invitation = undefined
  queryParams.admission = undefined
  queryParams.reserve = undefined

  switch (newValue) {
    case 'public':
      queryParams.permission = 'public'
      break
    case 'private':
      queryParams.permission = 'private'
      break
    case 'candidate':
      queryParams.candidate = true
      break
    case 'interview':
      queryParams.invitation = true
      break
    case 'admission':
      queryParams.admission = true
      break
    case 'improper':
      queryParams.admission = false
      break
    case 'reserve':
      queryParams.reserve = true
      break
  }
  if (newValue !== 'interview') {
    handleQuery()
  }
})

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const handleReset = () => {
  queryParams.name = undefined
  queryParams.activeState = undefined
  queryParams.jobName = undefined
  queryParams.jonLongStart = undefined
  queryParams.jonLongEnd = undefined
  queryParams.city = undefined
  queryParams.education = undefined
  handleQuery()
}

const openRuleConfigModal = () => {
  ruleConfigModalVisible.value = true
}

onMounted(() => {
  getList()
})

const formatActiveState = (state?: number) => {
  if (state === undefined || state === null) return ''
  switch (state) {
    case 0: return '刚刚活跃'
    case 1: return '今日活跃'
    case 3: return '3天活跃'
    case 7: return '本周活跃'
    case 30: return '本月活跃'
    default: return '未知'
  }
}

const formatSex = (sex?: number) => {
  if (sex === undefined || sex === null) return ''
  switch (sex) {
    case 1: return '男'
    case 2: return '女'
    default: return '未知'
  }
}

const activeStateOptions = [
  { value: 0, label: '刚刚活跃' },
  { value: 1, label: '今日活跃' },
  { value: 3, label: '3天活跃' },
  { value: 7, label: '本周活跃' },
  { value: 30, label: '本月活跃' }
]

// 工具函数：转换时间戳为日期字符串 (YYYY-MM-DD)
const formatDate = (timestamp?: number) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化日期部分 (YYYY.MM)
const formatDateToYearMonth = (dateStr?: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    if (date.getFullYear() === 1970 && date.getMonth() === 0 && date.getDate() === 1) {
        return ''; 
    }
    if (date.getFullYear() < 1800 || date.getFullYear() > 2200) { 
       return '' 
    }
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    return `${year}.${month}`;
  } catch (e) {
    return ''; 
  }
};

// 格式化工作经历日期范围
const formatWorkDateRange = (startTimeStr?: string, endTimeStr?: string) => {
  const start = formatDateToYearMonth(startTimeStr);
  let end = '至今'; 

  if (endTimeStr) {
    const formattedEnd = formatDateToYearMonth(endTimeStr);
    if (formattedEnd) { 
      end = formattedEnd;
    }
  }
  
  if (!start && end === '至今') return '时间不详'; 
  if (!start) return end; 
  if (start === end && end !== '至今') return start; 
  if (start && end === '至今') return `${start} - 至今`;

  return `${start} - ${end}`;
};

// 格式化教育经历日期 (YYYY)
const formatEducationDate = (dateStr?: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    if (date.getFullYear() === 1970) return '';
    if (date.getFullYear() < 1800 || date.getFullYear() > 2200) return '';
    return date.getFullYear().toString();
  } catch (e) {
    return '';
  }
};

const handleRefreshStatus = async () => {
  try {
    // 显示加载中的消息
    const loadingMessage = ElMessage({
      message: '正在更新简历状态，请稍候...',
      type: 'info',
      duration: 0,
      showClose: true
    })
    
    // 调用API刷新简历状态
    await PersonnelResumeApi.refreshPersonnelResumeStatus()
    
    // 关闭加载消息
    loadingMessage.close()
    
    // 显示成功消息
    ElMessage.success('简历状态更新成功')
    
    // 重新加载数据
    getList()
  } catch (error) {
    console.error('Failed to refresh resume status:', error)
    ElMessage.error('简历状态更新失败，请重试')
  }
}

const showResumeDetail = async (id: string) => {
  try {
    // 获取简历拓展信息
    const resumeDetail = await PersonnelResumeApi.getPersonnelResumeExpand(id)
    
    // 如果存在html字段且是PDF链接
    if (resumeDetail && resumeDetail.html) {
      if (resumeDetail.html.startsWith('http') && 
         (resumeDetail.html.endsWith('.pdf') || resumeDetail.html.includes('aliyuncs.com'))) {
        
        // 使用fetch获取PDF文件流，解决Content-Disposition: attachment导致的下载问题
        try {
          const response = await fetch(resumeDetail.html)
          const blob = await response.blob()
          const url = URL.createObjectURL(blob)
          
          // 在弹窗中显示PDF
          resumeUrl.value = url
          resumeDetailVisible.value = true
        } catch (fetchError) {
          console.error('Failed to fetch PDF:', fetchError)
          ElMessage.warning('无法预览PDF，可能由于网络问题或者跨域限制')
          // 如果fetch失败，回退到在新窗口打开
          window.open(resumeDetail.html, '_blank')
        }
      } else {
        ElMessage.warning('简历格式不支持或链接无效')
      }
    } else {
      ElMessage.warning('未找到简历内容')
    }
  } catch (error) {
    console.error('Failed to get resume detail:', error)
    ElMessage.error('获取简历详情失败')
  }
}

// 更新单个简历状态
const handleRefreshSingleResume = async (id: string) => {
  try {
    // 显示加载中的消息
    const loadingMessage = ElMessage({
      message: '正在更新简历状态，请稍候...',
      type: 'info',
      duration: 0,
      showClose: true
    })
    
    // 调用API刷新单个简历状态
    await PersonnelResumeApi.refreshSingleResumeStatus(id)
    
    // 关闭加载消息
    loadingMessage.close()
    
    // 显示成功消息
    ElMessage.success('简历状态更新成功，请稍后刷新列表')
    
    // 重新加载数据
    getList()
  } catch (error) {
    console.error('Failed to refresh resume status:', error)
    ElMessage.error('简历状态更新失败，请重试')
  }
}

// 打开上传对话框
const openUploadDialog = () => {
  uploadDialogVisible.value = true
  uploadFiles.value = []
  
  // 获取AI模型列表
  if (aiModelOptions.value.length === 0) {
    fetchAiModels()
  } else if (aiModelOptions.value.length > 0) {
    // 默认选择第一个AI模型
    uploadForm.aiId = aiModelOptions.value[0].id
  }
}

// 文件选择变更
const handleFileChange = (file: any, fileList: any[]) => {
  uploadFiles.value = fileList.map(item => item.raw)
}

// 上传文件
const handleUpload = async () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请选择至少一个文件')
    return
  }
  
  if (!uploadForm.aiId) {
    ElMessage.warning('请选择AI模型')
    return
  }
  
  try {
    uploading.value = true
    
    // 调用上传API
    await PersonnelResumeApi.uploadResumes(uploadFiles.value, uploadForm.aiId)
    
    ElMessage.success('简历上传成功')
    uploadDialogVisible.value = false
    
    // 刷新列表
    getList()
  } catch (error) {
    console.error('Failed to upload resumes:', error)
    ElMessage.error('简历上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 处理入职状态
const handleNotJoined = (id: string) => {
  ElMessage.info(`牛人未入职: ${id}`)
  // 实际场景可以添加逻辑来处理未入职情况
}

const handleJoined = (id: string) => {
  ElMessage.info(`已确认入职: ${id}`)
  // 实际场景可以添加逻辑来处理已入职情况
}

const handleLeft = (id: string) => {
  ElMessage.info(`已确认离职: ${id}`)
  // 实际场景可以添加逻辑来处理已离职情况
}

// 查看报告
const showExpand = (id: string) => {
  ElMessage.info(`查看报告: ${id}`)
  // 实际场景中，可以调用API获取报告内容并展示
}

// 面试时间选择相关
const interviewDialogVisible = ref(false)
const interviewForm = reactive({
  resumeId: '',
  viewName: '',
  viewTime: '',
})

// 打开面试时间选择对话框
const openInterviewDialog = (id: string) => {
  interviewForm.resumeId = id
  interviewForm.viewName = ''
  interviewForm.viewTime = ''
  interviewDialogVisible.value = true
}

// 提交面试时间
const submitInterviewTime = async () => {
  if (!interviewForm.viewTime) {
    ElMessage.warning('请选择面试时间')
    return
  }
  
  try {
    await PersonnelResumeApi.createPersonnelInterview({
      resumeId: interviewForm.resumeId,
      viewName: interviewForm.viewName,
      viewTime: interviewForm.viewTime
    })
    
    ElMessage.success('面试时间设置成功')
    interviewDialogVisible.value = false
    
    // 刷新列表
    getList()
  } catch (error) {
    console.error('Failed to set interview time:', error)
    ElMessage.error('面试时间设置失败，请重试')
  }
}

// 简历详情预览相关
const resumeDetailVisible = ref(false)
const resumeUrl = ref('')

</script>
<style lang="scss" scoped>
.search-bar {
  margin-bottom: 16px;
}

.filter-form {
  :deep(.el-form-item) {
    margin-bottom: 10px;
  }
  :deep(.el-select) {
    width: 180px;
  }
}

.action-buttons {
  margin-bottom: 16px;
}

.resume-list {
  .resume-item {
    margin-bottom: 16px;
    .resume-header {
      margin-bottom: 8px;
      .name {
        font-size: 16px;
        font-weight: bold;
        margin-right: 8px;
      }
      .job-title {
        margin-left: 8px;
        margin-right: 8px;
        color: #333;
      }
      .phone {
        color: #666;
      }
      .el-tag {
        margin-left: 8px;
      }
      // 新增私库头部样式
      .update-time-display {
        margin-left: 15px;
        font-size: 12px;
        color: #666;
      }
      .matching-score {
        margin-left: 15px;
        font-size: 12px;
        color: #E6A23C; // Element Plus warning color for visibility
        font-weight: bold;
      }
    }
    .basic-info {
      margin-bottom: 8px;
      color: #666;
      font-size: 14px;
      span {
        margin-right: 5px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    // 旧的工作经验/教育背景样式
    .experience-list {
      margin-bottom: 8px;
      .experience-item {
        margin-bottom: 4px;
        font-size: 14px;
        color: #333;
        .job {
          color: #666;
          margin-left: 8px;
        }
      }
    }
    .education-item {
      font-size: 14px;
      color: #333;
      .major {
        margin-left: 8px;
        color: #666;
      }
      .degree {
        margin-left: 8px;
        color: #666;
      }
    }
    // 私库特定工作/教育样式
    .experience-list-private {
      margin-top: 8px;
      font-size: 13px; 
      color: #333;
      .experience-item-private, .education-item-private {
        margin-bottom: 5px;
        line-height: 1.6;
        .date-range { margin-right: 8px; color: #555; }
        .company, .school { margin-right: 8px; font-weight: 500; }
        .role, .major { margin-right: 8px; }
      }
    }
    // 工作经历样式
    .work-experience-list {
      margin-top: 8px;
      font-size: 14px;
      .section-title {
        font-weight: 500; 
        color: #333;
        margin-bottom: 4px;
      }
      .work-experience-item {
        font-size: 13px;
        color: #555;
        margin-bottom: 6px;
        p {
          margin: 2px 0; 
          line-height: 1.5; 
        }
        strong {
          color: #222;
          font-weight: 500;
        }
      }
    }

    // 教育经历样式
    .education-experience-list {
      margin-top: 12px;
      font-size: 14px;
      .section-title {
        font-weight: 500; 
        color: #333;
        margin-bottom: 4px;
      }
      .education-experience-item {
        font-size: 13px;
        color: #555;
        margin-bottom: 6px;
        p {
          margin: 2px 0; 
          line-height: 1.5; 
        }
      }
    }

    .resume-actions {
      font-size: 14px;
      .skills {
        margin-bottom: 12px;
        span {
          display: block;
          margin-bottom: 4px;
        }
        .tags-container {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.el-tag) {
          max-width: none;
          width: auto;
          border-radius: 12px;
          padding: 0 10px;
          height: 24px;
          line-height: 22px;
          background-color: #ecf5ff;
        }
      }
      .advantages {
        margin-bottom: 12px;
        span {
          display: block;
          margin-bottom: 4px;
        }
        .advantage-content {
          background-color: #f8f8f8;
          border-radius: 4px;
          padding: 8px;
          min-height: 50px;
          margin-top: 4px;
          font-size: 13px;
          line-height: 1.5;
        }
      }
      .update-info {
        margin-bottom: 8px;
        color: #666;
        .el-link {
          margin-left: 8px;
        }
      }
      .private-actions {
        margin-bottom: 12px;
        .el-link {
          font-size: 14px;
          color: #409EFF;
          line-height: 24px;
        }
      }
    }
    // AI 评语区域
    .ai-comment-section {
      margin-top: 10px;
      padding: 10px;
      background-color: #f8f8f8;
      border-radius: 4px;
      strong {
        display: block;
        margin-bottom: 5px;
        color: #333;
      }
      p {
        font-size: 13px;
        color: #555;
        line-height: 1.6;
        white-space: pre-wrap; // 保持换行
        margin: 0;
      }
    }
  }
}

.interview-time {
  color: #409EFF;
  margin-left: 15px;
  font-size: 12px;
}

.admission-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.evaluation-section,
.hr-evaluation-section {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  
  strong {
    display: block;
    margin-bottom: 5px;
    color: #333;
  }
  
  p {
    font-size: 13px;
    color: #555;
    line-height: 1.6;
    white-space: pre-wrap; // 保持换行
    margin: 0;
  }
}

.improper-reasons {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
}

.experience-list-improper {
  margin-top: 15px;
  
  .experience-item, .education-item {
    margin-bottom: 8px;
    font-size: 13px;
    color: #333;
    
    .date-range {
      margin-right: 8px;
      color: #666;
    }
    
    .company, .school {
      margin-right: 8px;
      font-weight: 500;
    }
    
    .role, .major, .degree {
      margin-right: 8px;
    }
  }
}
</style>
